﻿#include "tcpclient.h"
#include <QThread>
#pragma execution_character_set("utf-8")

//void TcpClient::(*acc_data_msg);
//static void TcpClient::(*acc_cali_msg)(mavlink_message_t &msg);

TcpClient::TcpClient(QObject *parent):QTcpSocket(parent)
{
//    connect(this,&QTcpSocket::readyRead,this,&TcpClient::receiveData);
}

TcpClient::~TcpClient()
{

}

void TcpClient::connectToServer(QString ip, int port)
{
    qDebug()<<ip<<port;
    connectToHost(ip,port);
//    mode = START1;
//    data.clear();
//    connect(this,&QTcpSocket::readyRead,this,&TcpClient::receiveData);
//    //connect(this,&QTcpSocket::disconnected,this,&TcpClient::disconnectServer);
//    plainText->clear();
//    plainText->appendPlainText("Success");
}
void TcpClient::disconnectServer()
{
    abort();
    disconnectFromHost();
    close();
//    disconnect(this,&QTcpSocket::readyRead,this,&TcpClient::receiveData);
    //disconnect(this,&QTcpSocket::disconnected,this,&TcpClient::disconnectServer);
//    plainText->clear();
//    plainText->appendPlainText("与服务器断开连接");
}

void TcpClient::receiveData()
{
    QByteArray buf;
    buf = readAll();
//    qDebug()<<QThread::currentThreadId();
    mavlink_status_t status;
    mavlink_message_t msg;
    for(int i = 0; i < buf.size();i++)
    {
        if(mavlink_parse_char(MAVLINK_COMM_0,static_cast<unsigned char>(buf.at(i)),&msg,&status)){

            switch (msg.msgid) {
            case MAVLINK_MSG_ID_ACC_DATA:
//                qDebug()<<msg.msgid;
                acc_data_msg(msg);
                break;
            case MAVLINK_MSG_ID_ACC_CALIB:
                acc_cali_msg(msg);
                qDebug()<<msg.msgid;
                emit received_cali();
                break;
//            case MAVLINK_MSG_ID_ACC_CMD:
//                break;
            }
        }
    }
}
void TcpClient::accCmdWrite(uint8_t cmd)
{
    mavlink_message_t msg;
    char buf[512];
    uint16_t len;
    switch (cmd) {
    case GET_CALIB:
        mavlink_msg_acc_cmd_pack(1,1,&msg,GET_CALIB);
        len = mavlink_msg_to_send_buffer((uint8_t *)buf, &msg);
        write(buf,len);
        break;
    case SAVE_CALIB:
        mavlink_msg_acc_cmd_pack(1,1,&msg,SAVE_CALIB);
        len = mavlink_msg_to_send_buffer((uint8_t *)buf, &msg);
        write(buf,len);
        /*********/
        msg = tx_cali_msg();
        len = mavlink_msg_to_send_buffer((uint8_t *)buf, &msg);
        write(buf,len);
        /*********/
        break;
    case START_TX:
        mavlink_msg_acc_cmd_pack(1,1,&msg,START_TX);
        len = mavlink_msg_to_send_buffer((uint8_t *)buf, &msg);
        write(buf,len);
        break;
    case STOP_TX:
        mavlink_msg_acc_cmd_pack(1,1,&msg,STOP_TX);
        len = mavlink_msg_to_send_buffer((uint8_t *)buf, &msg);
        write(buf,len);
        break;
    }


}
void TcpClient::receiveFailed()
{
    mode =  START1;
    data.clear();
}
void TcpClient::receiveSuccess()
{
    mode =  START1;
    data.clear();
}
